package partner_admin

import (
	"gitee.com/theegg/go-brick/app/controller/partner_api"
	"gitee.com/theegg/go-brick/app/model/partner/partner_admin/partner_admin_users"
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

// 登陆
func Login(c *gin.Context) {
	email := c.PostForm("username")
	password := c.PostForm("password")

	if ok, errCheck := partner_admin_users.HasUserFromEmail(email); !ok {
		app.NewResponse(c).JsonReturn(false, errCheck.Error(), nil)
		return
	}

	partnerAdminUser, errLogin := partner_admin_users.UserLogin(email, password, c.ClientIP())
	if errLogin != nil {
		app.NewResponse(c).JsonReturn(false, app.NewError(errLogin).Error(), nil)
		return
	}

	// 生成token
	token, errToken := partnerAdminUser.GenToken()
	if errToken != nil {
		app.NewResponse(c).JsonReturn(false, "登陆失败!", nil)
		return
	}

	returnData := map[string]interface{}{
		"token":      token,
		"expired_at": time.Now().Unix() + 86400,
	}

	app.NewResponse(c).JsonReturn(true, "登陆成功!", returnData)
	return
}

// @title 基础信息
func BaseInfo(c *gin.Context) {
	currentPau := partner_api.GetLoginPartnerAdminUser(c)
	menus, err := currentPau.GetMenuFromRole()

	if err != nil {
		app.NewResponse(c).JsonReturn(false, "获取数据失败-"+err.Error(), "")
		return
	}

	permissions, err := currentPau.GetPermissionFromRole()

	if err != nil {
		app.NewResponse(c).JsonReturn(false, "获取数据失败-"+err.Error(), "")
		return
	}

	// 整理过滤
	permissionData := make([]string, 0)
	for _, v := range permissions {
		if v == "" {
			continue
		}
		afterV := strings.ReplaceAll(v, `/mpi/`, "")
		permissionData = append(permissionData, afterV)
	}

	returnData := map[string]interface{}{
		"menus":        menus,
		"name":         currentPau.Username,
		"avatar":       app.GetImageStaticUrl(currentPau.ImageAvatar),
		"permissions":  permissionData,
		"role":         []int64{},
		"env":          app.Config.AppEnv,
		"default_lang": currentPau.GetLang(),
	}

	app.NewResponse(c).JsonReturn(true, "获取数据成功", returnData)
	return
}

// 登出
func Logout(c *gin.Context) {
	app.NewResponse(c).JsonReturn(true, "登出成功!", nil)
	return
}
